<?php

namespace app\admin\model;

use app\common\model\MoneyLog;
use think\Model;


class Order extends Model
{

    

    

    // 表名
    protected $name = 'order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];


    public function getPayStatus()
    {
        return [
            2 => '已支付',
            3 => '已退款',
        ];
    }
    public function user()
    {
        return $this->hasOne(IdentityInfo::class, 'user_id', 'user_id', [], 'LEFT')->where(['identity_type'=>'校方'])->setEagerlyType(0);
    }
    public function teacher()
    {
        return $this->hasOne(IdentityInfo::class, 'user_id', 'teacher_id', [], 'LEFT')->where(['identity_type'=>'教师'])->setEagerlyType(0);
    }
    public function teachers()
    {
        return $this->hasOne(IdentityInfo::class, 'user_id', 'teacher_id')->with(['user'])->where(['identity_type'=>'教师']);
    }
    public function address(){
        return $this->hasOne(ClassAddress::class,'id','address_id',[],'LEFT')->setEagerlyType(0);
    }
    public function dtl(){
        return $this->hasMany(OrderClassHours::class,'order_id','id');
    }

    public function classmain(){
        return $this->hasOne(TeacherClass::class,'order_no','order_no')->with(['dtls']);
    }

    //获取订单号
    public static function get_order_no($user_id){
        $number = str_pad($user_id, 6, "0", STR_PAD_LEFT);
        $order_no = 'P'.date('YmdHis').$number.rand(1000,9999);
        $find = Order::where(['order_no'=>$order_no])->find();
        if($find){
            self::get_order_no($user_id);
        }else{
            return $order_no;
        }
    }

    //支付完成
    public static function pay_success($order_no,$sanfang='',$type = '')
    {
        $find = Order::where(['order_no' => $order_no])->find();
        if (!$find) {
            return ['code'=>0,'msg'=>'订单不存在'];
        }
        $update = [];
        $update['pay_status'] = 2;
        if($sanfang){
            $update['snafang'] = $sanfang;
        }
        if($type){
            $update['type'] = $type;
        }
        //更新订单数据状态
        Order::where(['order_no' => $order_no])->update($update);
        $club_two = '';
        $club_two_name = '';
        if(isset($find['info'])&&$find['info']){
            $teacher_info = json_decode($find['info'],true);
            if(isset($teacher_info['club_two'])&&$teacher_info['club_two']){
                $club_two = '"'.$teacher_info['club_two'].'"';
                $club_two_name = $teacher_info['club_two'];
            }
        }

        //生成课程
        $add_teacher_class = [];
        $add_teacher_class['teacher_id'] = $find['teacher_id'];//教师user_id
        $add_teacher_class['user_id'] = $find['user_id'];//用户user_id
        $add_teacher_class['order_no'] = $find['order_no'];//订单编号

        $order_dtl = OrderClassHours::where(['order_id'=>$find['id']])->select();
        $class_num_all = 0;
        $period_set = 1;
        if($find['sign_type'] == '长期'){
            foreach ($order_dtl as $k=>$v){
                $class_num_all = precisionRestore($class_num_all,$v['semester_hours'],'加法');
            }
        }
        if($find['sign_type'] == '短期'){
            foreach ($order_dtl as $k=>$v){
                $class_num_all = precisionRestore($class_num_all,$v['class_num'],'加法');
            }
            $period_set = 2;
        }
        $add_teacher_class['class_num_all'] = $class_num_all;//总课时
        $add_teacher_class['completed_class_num'] = 0;//已完成课时
        $add_teacher_class['address_id'] = $find['address_id'];//上课地点
        if($find['sign_type'] == '短期'){
            $add_teacher_class['class_period'] = count($order_dtl).'天';
        }else{
            $add_teacher_class['class_period'] = '暂无计划';//课程周期
        }
        $add_teacher_class['money'] = $find['money'];//课程费用
        $add_teacher_class['period_set'] = $period_set;//周期设置(1每周 2日期 3每两周 4每月)
        $add_teacher_class['status'] = 1;//状态 1未完成 2已完成
        $add_teacher_class['club_two_name'] = $club_two_name;//社团名称
        $class_id = TeacherClass::insertGetId($add_teacher_class);

        if($find['sign_type'] == '短期'){
            $dtl_arr = [];
            foreach ($order_dtl as $k=>$v){
                $dtl_arr[$k]['teacher_class_id'] = $class_id;//课程id
                $dtl_arr[$k]['week_date'] = $v['class_date'];//日/周
                $dtl_arr[$k]['time_start'] = $v['class_start_time'];//开始时间
                $dtl_arr[$k]['class_num'] = $v['class_num'];//课时
                $dtl_arr[$k]['cycle'] = 2;//周期 1每周 2日期
                $dtl_arr[$k]['status'] = 1;//状态 1未开始 2已完成
            }
            TeacherClassDtl::insertAll($dtl_arr);
        }

        //给校方发通知 预约成功 前往制定课程计划
        $send_add_notice = [];
        $send_add_notice['title'] = '课程预约成功';//标题
        $send_add_notice['content'] = '您已成功预约'.$club_two.'课程,请进入课程详情制定具体的课程计划吧！';//内容
        $send_add_notice['need_confirm'] = 2;//是否需要确认 1是 2否
        $send_add_notice['jump'] = '课程详情';//跳转地址
        $send_add_notice['teacher_class_id'] = $class_id;//课程id
        $send_add_notice['teacher_class_dtl_id'] = 0;//课程安排id
        $send_add_notice['send_user_id'] = $find['user_id'];//发送人id
        $send_add_notice['get_user_id'] = $find['user_id'];//接收人id
        $send_add_notice['identity_type'] = '校方';//接收人身份
        $send_add_notice['addtime'] = date('Y-m-d H:i:s');//添加时间
        $send_add_notice['is_read'] = 1;//是否已读 1未读 2已读
        Notice::insertGetId($send_add_notice);
        // 发送个推消息
        Notice::sendGetuiPush($send_add_notice);

        $identity_info = IdentityInfo::where(['user_id'=>$find['user_id'],'identity_type'=>'校方'])->find();
        if($identity_info){
            $school = $identity_info['school'] ? $identity_info['school'] : '';
            $name = $identity_info['name'] ? $identity_info['name'] : '';
            $content = $school.$name.'已成功预约您的课程,请进入课程表查看详细的课程计划吧';
        }else{
            $content = '有学校已成功预约您的课程,请进入课程表查看详细的课程计划吧';
        }
        //给教师发通知 告知有人买课了
        $send_add_notice = [];
        $send_add_notice['title'] = '您有新的订单';//标题
        $send_add_notice['content'] = $content;//内容
        $send_add_notice['need_confirm'] = 2;//是否需要确认 1是 2否
        $send_add_notice['jump'] = '课程详情';//跳转地址
        $send_add_notice['teacher_class_id'] = $class_id;//课程id
        $send_add_notice['teacher_class_dtl_id'] = 0;//课程安排id
        $send_add_notice['send_user_id'] = $find['user_id'];//发送人id
        $send_add_notice['get_user_id'] = $find['teacher_id'];//接收人id
        $send_add_notice['identity_type'] = '教师';//接收人身份
        $send_add_notice['addtime'] = date('Y-m-d H:i:s');//添加时间
        $send_add_notice['is_read'] = 1;//是否已读 1未读 2已读
        Notice::insertGetId($send_add_notice);
        // 发送个推消息
        Notice::sendGetuiPush($send_add_notice);

        //把收入增加到教师钱包
        $money = $find['money'] ? (double)$find['money'] : 0;
        if($money){
            $teacher = User::where(['id'=>$find['teacher_id']])->find();
            $all_money = precisionRestore($teacher['money'],$money,'加法');
            $money_log = [];
            $money_log['user_id'] = $find['teacher_id'];//会员ID
            $money_log['money'] = $money;//变更余额
            $money_log['before'] = $teacher['money'];//变更前余额
            $money_log['after'] = $all_money;//变更后余额
            $money_log['memo'] = '课程费用';//备注
            $money_log['createtime'] = time();//创建时间
            $money_log['order_id'] = $find['id'];//订单id
            MoneyLog::insert($money_log);
            User::where(['id'=>$find['teacher_id']])->update(['money'=>$all_money]);
        }

        return ['code'=>1,'msg'=>'完成'];
    }
    public static function pay_success_new($order_no,$sanfang='',$type = '')
    {
        $find = Order::where(['order_no' => $order_no])->find();
        if (!$find) {
            return ['code'=>0,'msg'=>'订单不存在'];
        }
        $update = [];
        $update['pay_status'] = 2;
        if($sanfang){
            $update['snafang'] = $sanfang;
        }
        if($type){
            $update['type'] = $type;
        }
        //更新订单数据状态
        Order::where(['order_no' => $order_no])->update($update);
        $club_two = '';
        $club_two_name = '';
        if(isset($find['info'])&&$find['info']){
            $teacher_info = json_decode($find['info'],true);
            if(isset($teacher_info['club_two'])&&$teacher_info['club_two']){
                $club_two = '"'.$teacher_info['club_two'].'"';
                $club_two_name = $teacher_info['club_two'];
            }
        }

        //生成课程
        $add_teacher_class = [];
        $add_teacher_class['teacher_id'] = $find['teacher_id'];//教师user_id
        $add_teacher_class['user_id'] = $find['user_id'];//用户user_id
        $add_teacher_class['order_no'] = $find['order_no'];//订单编号

        $order_dtl = OrderClassHours::where(['order_id'=>$find['id']])->select();
        $class_num_all = 0;
        $period_set = 1;
        $week_num = 0;
        $start_date = '';
        $semester_arr = [
            1=>'一学期',
            2=>'两学期',
            3=>'三学期',
            4=>'四学期',
            5=>'五学期',
            6=>'六学期',
        ];
        $semester = '';
        if($find['sign_type'] == '长期'){
            foreach ($order_dtl as $k=>$v){
                $class_num_all = $v['semester_hours'];
                $week_num = $v['week_num'];
                if ($v['start_date'] && ($start_date === '' || strtotime($v['start_date']) < strtotime($start_date))) {
                    $start_date = $v['start_date'];
                }
                $semester = isset($semester_arr[$v['semester']]) ? $semester_arr[$v['semester']] : '';
            }
        }
        if($find['sign_type'] == '短期'){
            foreach ($order_dtl as $k=>$v){
                $class_num_all = precisionRestore($class_num_all,$v['class_num'],'加法');
                if ($v['class_date'] && ($start_date === '' || strtotime($v['class_date']) < strtotime($start_date))) {
                    $start_date = $v['class_date'];
                }
            }
            $period_set = 2;
        }
        $add_teacher_class['class_num_all'] = $class_num_all;//总课时
        $add_teacher_class['completed_class_num'] = 0;//已完成课时
        $add_teacher_class['address_id'] = $find['address_id'];//上课地点
        if($find['sign_type'] == '短期'){
            $add_teacher_class['class_period'] = count($order_dtl).'天';
        }else{
            $add_teacher_class['class_period'] = $week_num.'周';//课程周期
        }
        $add_teacher_class['money'] = $find['money'];//课程费用
        $add_teacher_class['period_set'] = $period_set;//周期设置(1每周 2日期 3每两周 4每月)
        $add_teacher_class['status'] = 1;//状态 1未完成 2已完成
        $add_teacher_class['club_two_name'] = $club_two_name;//社团名称
        $add_teacher_class['start_date'] = $start_date;
        $add_teacher_class['semester'] = $semester;
        $class_id = TeacherClass::insertGetId($add_teacher_class);

//        if($find['sign_type'] == '短期'){
            $dtl_arr = [];
            foreach ($order_dtl as $k=>$v){
                $dtl_arr[$k]['teacher_class_id'] = $class_id;//课程id
                $dtl_arr[$k]['week_date'] = $v['class_date'];//日/周
                $dtl_arr[$k]['time_start'] = $v['class_start_time'];//开始时间
                $dtl_arr[$k]['class_num'] = $v['class_num'];//课时
                $dtl_arr[$k]['cycle'] = 2;//周期 1每周 2日期
                $dtl_arr[$k]['status'] = 1;//状态 1未开始 2已完成
                if($find['sign_type'] == '短期'){
                    $dtl_arr[$k]['date'] = $v['class_date'];
                }else{
                    $dtl_arr[$k]['date'] = self::calculateTargetDate($start_date,$v['class_date']);
                }
            }
            TeacherClassDtl::insertAll($dtl_arr);
//        }

        //给校方发通知 预约成功 前往制定课程计划
        $send_add_notice = [];
        $send_add_notice['title'] = '课程预约成功';//标题
        $send_add_notice['content'] = '您已成功预约'.$club_two.'课程,请进入课程详情制定具体的课程计划吧！';//内容
        $send_add_notice['need_confirm'] = 2;//是否需要确认 1是 2否
        $send_add_notice['jump'] = '课程详情';//跳转地址
        $send_add_notice['teacher_class_id'] = $class_id;//课程id
        $send_add_notice['teacher_class_dtl_id'] = 0;//课程安排id
        $send_add_notice['send_user_id'] = $find['user_id'];//发送人id
        $send_add_notice['get_user_id'] = $find['user_id'];//接收人id
        $send_add_notice['identity_type'] = '校方';//接收人身份
        $send_add_notice['addtime'] = date('Y-m-d H:i:s');//添加时间
        $send_add_notice['is_read'] = 1;//是否已读 1未读 2已读
        Notice::insertGetId($send_add_notice);
        // 发送个推消息
        Notice::sendGetuiPush($send_add_notice);

        $identity_info = IdentityInfo::where(['user_id'=>$find['user_id'],'identity_type'=>'校方'])->find();
        if($identity_info){
            $school = $identity_info['school'] ? $identity_info['school'] : '';
            $name = $identity_info['name'] ? $identity_info['name'] : '';
            $content = $school.$name.'已成功预约您的课程,请进入课程表查看详细的课程计划吧';
        }else{
            $content = '有学校已成功预约您的课程,请进入课程表查看详细的课程计划吧';
        }
        //给教师发通知 告知有人买课了
        $send_add_notice = [];
        $send_add_notice['title'] = '您有新的订单';//标题
        $send_add_notice['content'] = $content;//内容
        $send_add_notice['need_confirm'] = 2;//是否需要确认 1是 2否
        $send_add_notice['jump'] = '课程详情';//跳转地址
        $send_add_notice['teacher_class_id'] = $class_id;//课程id
        $send_add_notice['teacher_class_dtl_id'] = 0;//课程安排id
        $send_add_notice['send_user_id'] = $find['user_id'];//发送人id
        $send_add_notice['get_user_id'] = $find['teacher_id'];//接收人id
        $send_add_notice['identity_type'] = '教师';//接收人身份
        $send_add_notice['addtime'] = date('Y-m-d H:i:s');//添加时间
        $send_add_notice['is_read'] = 1;//是否已读 1未读 2已读
        Notice::insertGetId($send_add_notice);
        // 发送个推消息
        Notice::sendGetuiPush($send_add_notice);

        //把收入增加到教师钱包
        $money = $find['money'] ? (double)$find['money'] : 0;
        if($money){
            $teacher = User::where(['id'=>$find['teacher_id']])->find();
            $all_money = precisionRestore($teacher['money'],$money,'加法');
            $money_log = [];
            $money_log['user_id'] = $find['teacher_id'];//会员ID
            $money_log['money'] = $money;//变更余额
            $money_log['before'] = $teacher['money'];//变更前余额
            $money_log['after'] = $all_money;//变更后余额
            $money_log['memo'] = '课程费用';//备注
            $money_log['createtime'] = time();//创建时间
            $money_log['order_id'] = $find['id'];//订单id
            MoneyLog::insert($money_log);
            User::where(['id'=>$find['teacher_id']])->update(['money'=>$all_money]);
        }
        // order_num字段自增1
        TeacherDetail::where(['id'=>$find['teacher_detail_id']])->setInc('order_num', 1);
        $td = TeacherDetail::where(['id'=>$find['teacher_detail_id']])->find();
        if($td){
            IdentityInfo::where(['id'=>$td['info_id']])->setInc('order_num_all',1);
        }
        return ['code'=>1,'msg'=>'完成'];
    }

    public static function calculateTargetDate($start_date, $target_weekday) {
        // 验证开始日期格式
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $start_date)) {
            return "错误：开始日期格式不正确，请使用YYYY-MM-DD格式";
        }

        // 定义星期映射关系
        $weekday_map = [
            '周一' => 0, '星期二' => 1, '周二' => 1,
            '周三' => 2, '星期三' => 2,
            '周四' => 3, '星期四' => 3,
            '周五' => 4, '星期五' => 4,
            '周六' => 5, '星期六' => 5,
            '周日' => 6, '星期日' => 6, '周天' => 6,'星期天' => 6
        ];

        // 检查目标星期参数是否有效
        if (!isset($weekday_map[$target_weekday])) {
            return "错误：无效的星期参数，请使用如'周一'、'周二'等格式";
        }

        $target_weekday_num = $weekday_map[$target_weekday];

        // 获取开始日期的星期几（0为周日，1-6为周一到周六）
        $start_weekday = date('w', strtotime($start_date));
        // 将周日的0转换为6，统一为0-5表示周一到周六，6表示周日
        if ($start_weekday == 0) {
            $start_weekday = 6;
        } else {
            $start_weekday = $start_weekday - 1;
        }
        // 计算天数差
        $day_diff = $target_weekday_num - $start_weekday;

        // 如果目标星期在开始日期之前，需要加上7天来获取下一周的日期
        if ($day_diff < 0) {
            $day_diff += 7;
        }
        // 计算目标日期
        $target_date = date('Y-m-d', strtotime($start_date . " +{$day_diff} days"));

        return $target_date;
    }

    //退款
    public static function refund_success($order_no){
        //改课程状态
        $class = TeacherClass::where(['order_no'=>$order_no])->find();
        if(!$class){
            return ['code'=>0,'msg'=>'对应课程不存在'];
        }

        //钱包扣钱
        $order = Order::where(['order_no'=>$order_no])->find();
        if(!$class){
            return ['code'=>0,'msg'=>'对应课程不存在'];
        }
        User::where(['id'=>$class['teacher_id']])->setDec('money',$order['money']);
        $class->save(['status'=>3]);

        //发送通知
        $send_add_notice = [];
        $send_add_notice['title'] = '课程退款通知';//标题
        $send_add_notice['content'] = '您的课程订单已退款，课程状态改为已中止，钱包金额已扣除';//内容
        $send_add_notice['need_confirm'] = 2;//是否需要确认 1是 2否
        $send_add_notice['jump'] = '课程详情';//跳转地址
        $send_add_notice['teacher_class_id'] = $class['id'];//课程id
        $send_add_notice['teacher_class_dtl_id'] = 0;//课程安排id
        $send_add_notice['send_user_id'] = $class['user_id'];//发送人id
        $send_add_notice['get_user_id'] = $class['teacher_id'];//接收人id
        $send_add_notice['identity_type'] = '教师';//接收人身份
        $send_add_notice['addtime'] = date('Y-m-d H:i:s');//添加时间
        $send_add_notice['is_read'] = 1;//是否已读 1未读 2已读
        Notice::insertGetId($send_add_notice);

        $send_add_notice = [];
        $send_add_notice['title'] = '课程退款通知';//标题
        $send_add_notice['content'] = '您购买的课程订单已退款，课程状态改为已中止';//内容
        $send_add_notice['need_confirm'] = 2;//是否需要确认 1是 2否
        $send_add_notice['jump'] = '课程详情';//跳转地址
        $send_add_notice['teacher_class_id'] = $class['id'];//课程id
        $send_add_notice['teacher_class_dtl_id'] = 0;//课程安排id
        $send_add_notice['send_user_id'] = $class['user_id'];//发送人id
        $send_add_notice['get_user_id'] = $class['user_id'];//接收人id
        $send_add_notice['identity_type'] = '校方';//接收人身份
        $send_add_notice['addtime'] = date('Y-m-d H:i:s');//添加时间
        $send_add_notice['is_read'] = 1;//是否已读 1未读 2已读
        Notice::insertGetId($send_add_notice);
        // 发送个推消息
        Notice::sendGetuiPush($send_add_notice);

        //更改课程占用 改教师可约周
        TeacherSubscribe::class_success_up($class['id'],$class['teacher_id']);
        return ['code'=>1,'msg'=>'完成'];
    }

}
